package com.example.dense_rack_server.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.dense_rack_server.controller.Cellid;
import com.example.dense_rack_server.entity.*;
import com.example.dense_rack_server.mapper.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.dense_rack_server.security.dto.JwtUserDto;
import com.example.dense_rack_server.utils.CabinetLoginStatus;
import com.example.dense_rack_server.utils.DateFormat;
import com.example.dense_rack_server.utils.Netty.NettyServerHandler;
import com.example.dense_rack_server.utils.Netty.SendCmd;
import com.example.dense_rack_server.utils.ResponseModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.text.ParseException;
import java.util.*;

/**
 * <p>
 * 档案表 服务实现类
 * </p>
 *
 * @author 张彬
 * @since 2025-03-03
 */
@Slf4j
@Service
public class ArchivesService extends ServiceImpl<ArchivesMapper, Archives> {

    @Resource
    public ArchivesMapper archivesMapper;
    @Resource
    public HostService hostService;
    @Resource
    public ElectronArchivesMapper electronArchivesMapper;
    @Resource
    public ArchivesAreaMapper archivesAreaMapper;
    @Resource
    public BorrowingRecordsMapper borrowingRecordsMapper;
    @Resource
    public SendCmd sendCmd;
    @Resource
    public ArchivesTypeMapper archivesTypeMapper;
    @Autowired
    private SysParamsetMapper sysParamsetMapper;

    @Resource
    private CabinetLoginStatus cabinetLoginStatus;
    public String jobId = "";

    /**
     * 档案册数据
     **/
    public Map<String, Object> ArchiveList(String fileName, String archiveArea, String year, String areaId, int page, int limit) {
        Map<String, Object> paramsMap = new HashMap<>();
        if (StrUtil.isNotEmpty(archiveArea)) {
            List<Integer> areaIds = archivesAreaMapper.queryAllSubordinates(Convert.toInt(archiveArea));
            paramsMap.put("areaIds", areaIds);
        }
        if (StrUtil.isNotEmpty(fileName)) {
            paramsMap.put("fileName", fileName);
        }
        if (StrUtil.isNotEmpty(year)) {
            paramsMap.put("year", year);
        }
        if (StrUtil.isNotEmpty(areaId)) {
            paramsMap.put("areaId", areaId);
        }
        // 手动处理分页
        int offset = (page - 1) * limit;
        paramsMap.put("page", offset);
        paramsMap.put("limit", limit);
        List<Map<String, Object>> mapList = archivesMapper.archiveList(paramsMap);
        Map<String, Object> map = new HashMap<>();
        map.put("code", 0);
        map.put("msg", "数据请求成功");
        map.put("count", archivesMapper.archiveListCount(paramsMap));
        map.put("data", mapList);
        return map;
    }

    /**
     * 档案插入
     */
    public ResponseModel archiveInsert(@RequestBody JSONObject data) {
        Archives archivesDb = archivesMapper.selectOne(new QueryWrapper<Archives>()
                .eq("file_name", data.getStr("fileName")));
        if (archivesDb != null) {
            return ResponseModel.fail("档案已存在");
        }
        if (StrUtil.isNotEmpty(data.getStr("fileId"))) {
            Archives fileIdExists = archivesMapper.selectOne(new QueryWrapper<Archives>().eq("file_id", data.getStr("fileId")));
            if (fileIdExists != null) {
                return ResponseModel.fail("档案id已重复");
            }
        }
        Archives archives = new Archives();
        archives.setFileId(data.getStr("fileId"));
        archives.setFileName(data.getStr("fileName"));
        if (StrUtil.isNotEmpty(data.getStr("year"))) {
            archives.setYear(data.getStr("year"));
        } else {
            Date date = DateUtil.date();
            archives.setYear(Convert.toStr(DateUtil.year(date)));
        }
        archives.setUserName(data.getStr("userName"));
        archives.setProfile(data.getStr("profile"));
        archives.setStatus(data.getInt("fileStatus"));
        if (StrUtil.isNotEmpty(data.getStr("electronId"))) {
            archives.setElectronFileStatus(1);
        } else {
            archives.setElectronFileStatus(0);
        }
        archives.setArchivesAreaId(data.getInt("archiveArea"));
        archives.setArchivesTypeId(data.getInt("typeId"));
        archives.setCreateTime(DateFormat.getTime());
        archives.setUpdateTime(DateFormat.getTime());
        Host host = hostService.getById(data.getInt("hostId"));
        archives.setAreaCode(host.getCabinetNumber());
        archives.setColumnNumber(data.getInt("columnNumber"));
        archives.setDenseRackRegion(data.getInt("denseRackRegion"));
        archives.setJoint(data.getInt("joint"));
        archives.setLayerNumber(data.getInt("cabinetLayer"));
        archives.setPosition(data.getInt("position"));
        archives.setUuid(data.getStr("uuid"));
        int result = archivesMapper.insert(archives);
        if (StrUtil.isNotEmpty(data.getStr("electronId"))) {
            electronArchivesMapper.update(null, new UpdateWrapper<ElectronArchives>().eq("id", data.getInt("electronId"))
                    .set("archives_id", archives.getId()));
        }
        // 新增档案日志
        JwtUserDto jwtUserDto = (JwtUserDto) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String userName = jwtUserDto.getUsername();
        BorrowingRecords borrowingRecords = new BorrowingRecords();
        borrowingRecords.setFileId(archives.getId());
        borrowingRecords.setFileName(archives.getFileName());
        borrowingRecords.setDeptId(jwtUserDto.getMyUser().getDeptId());
        borrowingRecords.setUserName(userName);
        borrowingRecords.setRemarks(data.getStr("remarks"));
        borrowingRecords.setCreateTime(DateFormat.getTime());
        borrowingRecords.setDataStatus(5);
        borrowingRecords.setStatus(1);
        borrowingRecords.setModuleType(2);
        borrowingRecords.setOperation(userName + "用户新增" + archives.getFileName() + "档案");
        borrowingRecords.setHostId(host.getId());
        borrowingRecordsMapper.insert(borrowingRecords);

        return result > 0 ? ResponseModel.success("档案插入成功") : ResponseModel.fail("档案插入失败");
    }


    /**
     * 编辑保存
     */
    public ResponseModel editSave(JSONObject data) {
        Archives archivesDb = archivesMapper.selectOne(new QueryWrapper<Archives>()
                .eq("file_name", data.getStr("fileName")).ne("id", data.getInt("id")));
        if (archivesDb != null) {
            return ResponseModel.fail("档案已存在");
        }
        if (StrUtil.isNotEmpty(data.getStr("fileId"))) {
            Archives fileIdExists = archivesMapper.selectOne(new QueryWrapper<Archives>().eq("file_id", data.getStr("fileId"))
                    .ne("id", data.getInt("id")));
            if (fileIdExists != null) {
                return ResponseModel.fail("档案id已重复");
            }
        }
        UpdateWrapper<Archives> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", data.getInt("id"));
        updateWrapper.set("file_id", data.getStr("fileId"));
        updateWrapper.set("file_name", data.getStr("fileName"));
        if (StrUtil.isNotEmpty(data.getStr("year"))) {
            updateWrapper.set("year", data.getStr("year"));
        } else {
            Date date = DateUtil.date();
            updateWrapper.set("year", Convert.toStr(DateUtil.year(date)));
        }
        updateWrapper.set("user_name", data.getStr("userName"));
        updateWrapper.set("profile", data.getStr("profile"));
        updateWrapper.set("status", data.getInt("fileStatus"));
        updateWrapper.set("electron_file_status", 0);
        updateWrapper.set("archives_area_id", data.getInt("archiveArea"));
        updateWrapper.set("archives_type_id", data.getInt("typeId"));
        updateWrapper.set("create_time", DateFormat.getTime());
        updateWrapper.set("update_time", DateFormat.getTime());
        Host host = hostService.getById(data.getInt("hostId"));
        updateWrapper.set("area_code", host.getCabinetNumber());
        updateWrapper.set("column_number", data.getInt("columnNumber"));
        updateWrapper.set("dense_rack_region", data.getInt("denseRackRegion"));
        updateWrapper.set("joint", data.getInt("joint"));
        updateWrapper.set("layer_number", data.getInt("cabinetLayer"));
        updateWrapper.set("position", data.getInt("position"));
        int result = archivesMapper.update(null, updateWrapper);
        return result > 0 ? ResponseModel.success("档案保存成功") : ResponseModel.fail("档案保存失败");
    }

    /**
     * 档案详情
     */
    public ModelAndView archiveDetail(int archiveId) {
        ModelAndView modelAndView = new ModelAndView("archives/detail");
        Map<String, Object> archivesMap = archivesMapper.archiveDetail(archiveId);
        modelAndView.addObject("archives", archivesMap);
        // 获取区号
        Host host = hostService.getOne(new QueryWrapper<Host>().eq("cabinet_number", Convert.toInt(archivesMap.get("area_code"))));
        modelAndView.addObject("areaCode", "载体名称: " + host.getCabinetName() + " " + "区号: " + host.getCabinetNumber());
        String sysType = sysParamsetMapper.selectById(2).getParamValue();
        modelAndView.addObject("sysType", sysType);
        return modelAndView;
    }


    // 获取系统类型
    public String sysType() {
        SysParamset sysParamset = sysParamsetMapper.selectById(2);
        String sysType = sysParamset.getParamValue();
        return sysType;
    }

    /**
     * 地图柜借阅无需下发任务直接取出
     * 获取登录状态
     * 没有登录先登录
     * 登陆了就不用登录了
     *
     * @param host
     * @throws InterruptedException
     */
    public void loginStatus(Host host) throws InterruptedException {
        Map<String, Object> loginStatusMap = new LinkedHashMap<>();
        loginStatusMap.put("type", "serverLoginStatus");
        String loginStrMap = JSONUtil.toJsonStr(loginStatusMap);
        sendCmd.send(loginStrMap, null, host.getIp());
        while (true) {
            Thread.sleep(30);
            LinkedHashMap<String, Object> statusMap = cabinetLoginStatus.get();
            log.error("登录状态: " + statusMap);
            if (statusMap.containsKey("serverLoginStatus")) {
                Boolean loginStatus = Convert.toBool(statusMap.get("serverLoginStatus"));
                if (loginStatus) {
                    cabinetLoginStatus.del("serverLoginStatus");
                    break;
                } else {
                    log.info("远程登录");
                    Map<String, Object> loginMap = new LinkedHashMap<>();
                    loginMap.put("type", "serverLogin");
                    String loginMapStr = JSONUtil.toJsonStr(loginMap);
                    sendCmd.send(loginMapStr, null, host.getIp());
                    Thread.sleep(3000);
                    if (statusMap.containsKey("serverLoginStatus")) {
                        cabinetLoginStatus.del("serverLoginStatus");
                    }
                    break;
                }
            }
        }
    }

    /**
     * 地图柜
     */
    public String mapCabinetPosition(Archives archives) throws InterruptedException {
        Host host = hostService.getOne(new QueryWrapper<Host>().eq("cabinet_number", Convert.toInt(archives.getAreaCode())));
        loginStatus(host);
        Cellid cellid = new Cellid(archives.getAreaCode(), archives.getColumnNumber(), 1, archives.getJoint(), 1, archives.getPosition());
        String position = Convert.toStr(cellid.getId());
        return position;
    }

    /**
     * 档案删除
     */
    public ResponseModel deleteSave(String archiveId) throws InterruptedException {
        String[] strings = archiveId.split(",");
        List<String> idList = CollUtil.newArrayList(strings);
        for (String id : idList) {
            Archives archives = archivesMapper.selectById(id);
            String sysType = sysType();
            Map<String, Object> borrowingMap = new HashMap<>();
            String position = null;
            if (sysType.equals("1") || sysType.equals("3")) {
                // 档案在库下发取出任务
                if (archives.getStatus() == 0 || archives.getStatus() == 2) {
//                    if (sysType.equals("1") || sysType.equals("3")) {
                    borrowingMap.put("type", "task");
                    position = getPosition(archives, sysType);
                    borrowingMap.put("operation", "delete");
                    borrowingMap.put("filename", archives.getFileName());
                    borrowingMap.put("fileId", archives.getId()); //数据库自增id
                    borrowingMap.put("rfid", archives.getFileId());
                    borrowingMap.put("barcode", "");
                    borrowingMap.put("reserved", "");
//                    } else {
//                        borrowingMap.put("type", "open_lie_lock");
//                        position = mapCabinetPosition(archives);
//                    }
                    borrowingMap.put("position", position);
                    String lockStrMap = JSONUtil.toJsonStr(borrowingMap);
                    QueryWrapper<Host> hostQueryWrapper = new QueryWrapper<>();
                    hostQueryWrapper.eq("cabinet_number", archives.getAreaCode());
                    Host host = hostService.getOne(hostQueryWrapper);
                    sendCmd.send(lockStrMap, null, host.getIp());
                    // 开灯
                    openLen(position, host.getIp());
                } else {
                    archivesMapper.deleteById(archives.getId());
//            FileLogInsert.insert("档案管理", "删除" + archives.getFileName() + "档案", 3, archives.getNumber(), archives.getFileName());
                    electronArchivesMapper.delete(new QueryWrapper<ElectronArchives>().eq("archives_id", archives.getId()));
                }
            } else if (sysType.equals("2")) {
                borrowingMap.put("type", "open_lie_lock");
                position = mapCabinetPosition(archives);
                borrowingMap.put("position", position);
                String lockStrMap = JSONUtil.toJsonStr(borrowingMap);
                QueryWrapper<Host> hostQueryWrapper = new QueryWrapper<>();
                hostQueryWrapper.eq("cabinet_number", archives.getAreaCode());
                Host host = hostService.getOne(hostQueryWrapper);
                sendCmd.send(lockStrMap, null, host.getIp());
                // 开灯
                openLen(position, host.getIp());
                archivesMapper.deleteById(archives.getId());
//            FileLogInsert.insert("档案管理", "删除" + archives.getFileName() + "档案", 3, archives.getNumber(), archives.getFileName());
                electronArchivesMapper.delete(new QueryWrapper<ElectronArchives>().eq("archives_id", archives.getId()));
            }else {
                archivesMapper.deleteById(archives.getId());
                electronArchivesMapper.delete(new QueryWrapper<ElectronArchives>().eq("archives_id", archives.getId()));
            }
        }
        return ResponseModel.success("档案删除成功");
    }

    /**
     * 档案借阅
     */
    public ModelAndView takeoutView(String archiveId) {
        ModelAndView modelAndView = new ModelAndView("archives/takeout");
        Map<String, Object> archivesMap = archivesMapper.archiveDetail(Integer.valueOf(archiveId));
        modelAndView.addObject("archives", archivesMap);

        SysParamset sysParamset = sysParamsetMapper.selectById(2);
        modelAndView.addObject("sysType", sysParamset.getParamValue());
        return modelAndView;
    }

    /**
     * 普通密集架获取档案位置
     *
     * @param archives
     * @return
     */
    public String getPosition(Archives archives, String sysType) {
        StringBuilder position = new StringBuilder();
        int areaCode = archives.getAreaCode().toString().length();
        if (areaCode == 1) {
            position.append("0").append(archives.getAreaCode().toString());
        } else {
            position.append(archives.getAreaCode());
        }
        int columnNumber = archives.getColumnNumber().toString().length();
        if (columnNumber == 1) {
            position.append("0").append(archives.getColumnNumber().toString());
        } else {
            position.append(archives.getColumnNumber());
        }
        position.append(archives.getDenseRackRegion().toString())
                .append(archives.getJoint().toString());

        if (sysType.equals("1") || sysType.equals("3")) {
            position.append(archives.getLayerNumber().toString());
        } else {
            position.append("1");
        }

        int positionLength = archives.getPosition().toString().length();
        if (positionLength == 1) {
            position.append("0").append(archives.getPosition().toString());
        } else {
            position.append(archives.getPosition());
        }
        return position.toString();
    }


    /**
     * 地图柜档案位置
     *
     * @param archives
     * @return
     */
    public String getMapCabinetPosition(Archives archives) {
        StringBuilder position = new StringBuilder();
        int areaCode = archives.getAreaCode().toString().length();
        if (areaCode == 1) {
            position.append("0").append(archives.getAreaCode().toString());
        } else {
            position.append(archives.getAreaCode());
        }
        int columnNumber = archives.getColumnNumber().toString().length();
        if (columnNumber == 1) {
            position.append("0").append(archives.getColumnNumber().toString());
        } else {
            position.append(archives.getColumnNumber());
        }
        // dir 左右方向
        position.append("1");
        // 节
        position.append(archives.getDenseRackRegion().toString());
        // 层传1固定
        position.append("1");
        //位置
        int positionLength = archives.getPosition().toString().length();
        if (positionLength == 1) {
            position.append("0").append(archives.getPosition().toString());
        } else {
            position.append(archives.getPosition());
        }
        return position.toString();
    }

    /**
     * 获取设备状态
     */
    public boolean getDeviceStatus(Host host) {
        List<String> ipList = NettyServerHandler.getConnectionStatus();
        if (!ipList.contains(host.getIp())) {
            return false;
        }
        return true;
    }


    AutoLogoutTask autoLogoutTask;
    Timer timer;

    class AutoLogoutTask extends TimerTask {

        private String ip;

        public AutoLogoutTask(String ip) {
            this.ip = ip;
        }

        @Override
        public void run() {
            log.info("自动关灯");
            Map<String, Object> closeLed = new HashMap<>();
            closeLed.put("type", "task_guidexy_close");
            String closeLedStrMap = JSONUtil.toJsonStr(closeLed);
            sendCmd.send(closeLedStrMap, null, ip);
        }
    }

    private boolean isAutoLogoutTaskRunning = false;

    public void startAutoLogoutTask(String ip) {
        if (isAutoLogoutTaskRunning) {
            autoLogoutTask.cancel();
            autoLogoutTask = null;
            timer.cancel();
            timer = null;
        }
        timer = new Timer();
        autoLogoutTask = new AutoLogoutTask(ip);
        timer.schedule(autoLogoutTask, 1 * 60 * 1000);
        isAutoLogoutTaskRunning = true;
    }


    public void openLen(String position, String ip) {
//        CronUtil.remove(jobId);
//        log.info("即将发送关灯命令");
//        Map<String, Object> closeLed = new HashMap<>();
//        closeLed.put("type", "task_guidexy_close");
//        String closeLedStrMap = JSONUtil.toJsonStr(closeLed);
//        sendCmd.send(closeLedStrMap, null, ip);
        log.info("开灯position:{},ip:{}", position, ip);
        Map<String, Object> sendMap = new HashMap<>();
        sendMap.put("type", "task_guidexy");
        sendMap.put("position", position);
        String sendStrMap = JSONUtil.toJsonStr(sendMap);
        sendCmd.send(sendStrMap, null, ip);

        startAutoLogoutTask(ip);

        // 关键：开启秒级匹配（默认可能关闭）
//        CronUtil.setMatchSecond(true);
//        String cron = String.format("0 */%s * * * ?", 1);
//        log.info("cron表达式{}", cron);
//        jobId = CronUtil.schedule(cron, new Task() {
//            @Override
//            public void execute() {
//                 关灯
//                Map<String, Object> closeLed = new HashMap<>();
//                closeLed.put("type", "task_guidexy_close");
//                String closeLedStrMap = JSONUtil.toJsonStr(closeLed);
//                sendCmd.send(closeLedStrMap, null, ip);
//                log.info("关灯position:{},ip:{}",position,ip);
//                CronUtil.remove(jobId);
//            }
//        });
//         支持秒级别定时任务
//        CronUtil.start();
    }

    /**
     * 档案借阅保存
     */
    public ResponseModel takeOutSave(@RequestBody JSONObject data) throws InterruptedException {
        Archives archives = archivesMapper.selectById(data.getInt("id"));
        String sysType = sysType();
        QueryWrapper<Host> hostQueryWrapper = new QueryWrapper<>();
        hostQueryWrapper.eq("cabinet_number", archives.getAreaCode());
        Host host = hostService.getOne(hostQueryWrapper);
        if (!sysType.equals("4")) {
            // 设备状态检查
            if (!getDeviceStatus(host)) {
                return ResponseModel.fail("设备未连接，请确认设备开启状态");
            }
            // 下发借阅通知
            String position = null;
            Map<String, Object> borrowingMap = new HashMap<>();
            if (sysType.equals("1") || sysType.equals("3")) {
                borrowingMap.put("type", "task");
                position = getPosition(archives, sysType);
                borrowingMap.put("operation", "borrow");
                borrowingMap.put("filename", archives.getFileName());
                borrowingMap.put("fileId", archives.getId()); //数据库自增id
                borrowingMap.put("rfid", archives.getFileId());
                borrowingMap.put("barcode", "");
                borrowingMap.put("reserved", "");
            } else {
                borrowingMap.put("type", "open_lie_lock");
                position = mapCabinetPosition(archives);
            }
            borrowingMap.put("position", position);
            String lockStrMap = JSONUtil.toJsonStr(borrowingMap);
            sendCmd.send(lockStrMap, null, host.getIp());
            // 开灯
            openLen(position, host.getIp());
        }
        // 修改档案状态
        UpdateWrapper<Archives> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", data.getInt("id"));
        if (sysType.equals("1") || sysType.equals("3")) {
            updateWrapper.set("status", 2);
        } else {
            updateWrapper.set("status", 1);
        }
        updateWrapper.set("update_time", DateFormat.getTime());
        int result = archivesMapper.update(null, updateWrapper);
        if (result <= 0) {
            return ResponseModel.fail("档案借阅失败");
        }
        //添加借阅记录
        JwtUserDto jwtUserDto = (JwtUserDto) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String userName = jwtUserDto.getUsername();
        BorrowingRecords borrowingRecords = new BorrowingRecords();
        borrowingRecords.setFileId(archives.getId());
        borrowingRecords.setFileName(archives.getFileName());
        borrowingRecords.setDeptId(jwtUserDto.getMyUser().getDeptId());
        borrowingRecords.setUserName(userName);
        borrowingRecords.setRemarks(data.getStr("remarks"));
        borrowingRecords.setCreateTime(DateFormat.getTime());
        if (sysType.equals("1") || sysType.equals("3")) {
            borrowingRecords.setDataStatus(2);
        } else {
            borrowingRecords.setDataStatus(0);
        }
        borrowingRecords.setStatus(1);
        borrowingRecords.setModuleType(2);
        borrowingRecords.setOperation(userName + "用户借阅" + archives.getFileName() + "档案");
        borrowingRecords.setHostId(host.getId());
        borrowingRecordsMapper.insert(borrowingRecords);
        if (sysType.equals("1") || sysType.equals("3")) {
            return ResponseModel.success("请前往柜体端领取档案");
        } else {
            return ResponseModel.success("档案领取成功");
        }
    }

    /**
     * 归还档案保存
     */
    public ResponseModel returnSave(@RequestBody JSONObject data) throws InterruptedException {
        Archives archives = archivesMapper.selectById(data.getInt("archiveId"));
        String sysType = sysType();
        QueryWrapper<Host> hostQueryWrapper = new QueryWrapper<>();
        hostQueryWrapper.eq("cabinet_number", archives.getAreaCode());
        Host host = hostService.getOne(hostQueryWrapper);
        if (!sysType.equals("4")) {
            // 设备状态检查
            if (!getDeviceStatus(host)) {
                return ResponseModel.fail("设备未连接，请确认设备开启状态");
            }
            // 下发归还通知
            String position = null;
            Map<String, Object> restoreMap = new HashMap<>();
            if (sysType.equals("1") || sysType.equals("3")) {
                restoreMap.put("type", "task");
                position = getPosition(archives, sysType);
                restoreMap.put("operation", "restore");
                restoreMap.put("filename", archives.getFileName());
                restoreMap.put("fileId", archives.getId()); //数据库自增id
                restoreMap.put("rfid", archives.getFileId());
                restoreMap.put("barcode", "");
                restoreMap.put("reserved", "");
            } else {
                restoreMap.put("type", "open_lie_lock");
                position = mapCabinetPosition(archives);
            }
            restoreMap.put("position", position);
            String lockStrMap = JSONUtil.toJsonStr(restoreMap);
            sendCmd.send(lockStrMap, null, host.getIp());
            // 开灯
            openLen(position, host.getIp());
        }
        // 修改档案状态
        UpdateWrapper<Archives> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", archives.getId());
        if (sysType.equals("1") || sysType.equals("3")) {
            updateWrapper.set("status", 3);
        } else {
            updateWrapper.set("status", 0);
        }
        updateWrapper.set("update_time", DateFormat.getTime());
        int result = archivesMapper.update(null, updateWrapper);
        if (result <= 0) {
            return ResponseModel.fail("档案归还失败");
        }
        //添加借阅记录
        JwtUserDto jwtUserDto = (JwtUserDto) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String userName = jwtUserDto.getUsername();
        BorrowingRecords borrowingRecords = new BorrowingRecords();
        borrowingRecords.setFileId(archives.getId());
        borrowingRecords.setFileName(archives.getFileName());
        borrowingRecords.setDeptId(jwtUserDto.getMyUser().getDeptId());
        borrowingRecords.setUserName(userName);
        borrowingRecords.setRemarks(data.getStr("remarks"));
        borrowingRecords.setCreateTime(DateFormat.getTime());
        if (sysType.equals("1") || sysType.equals("3")) {
            borrowingRecords.setDataStatus(3);
        } else {
            borrowingRecords.setDataStatus(1);
        }
        borrowingRecords.setStatus(1);
        borrowingRecords.setModuleType(2);
        borrowingRecords.setOperation(userName + "用户归还" + archives.getFileName() + "档案");
        borrowingRecords.setHostId(host.getId());
        borrowingRecordsMapper.insert(borrowingRecords);
        if (sysType.equals("1") || sysType.equals("3")) {
            return ResponseModel.success("请前往柜体端归还档案");
        } else {
            return ResponseModel.success("档案归还成功");
        }
    }

    /**
     * 档案类型统计
     *
     * @return
     */
    public Map<String, Object> archiveTypeStatistics() {
        List<ArchivesType> archivesTypeList = null;
        Date nowDate = DateUtil.date();
        Map<String, Integer> monthMap = null;
        archivesTypeList = archivesTypeMapper.getInThePast6Months();
        Date newDate = DateUtil.offset(nowDate, DateField.MONTH, -6);
        monthMap = new LinkedHashMap<String, Integer>() {
            {
                for (int i = 0; i <= 6; i++) {
                    Date offsetNewDate = DateUtil.offset(newDate, DateField.MONTH, i);
                    int year = DateUtil.year(offsetNewDate);
                    int month = DateUtil.month(offsetNewDate) + 1;
                    put(year + "-" + month + "月", 0);
                }
            }
        };
        for (ArchivesType archivesType : archivesTypeList) {
            Date date = DateUtil.parse(archivesType.getCreateTime(), "yyyy-MM-dd");
            int year = DateUtil.year(date);
            int month = DateUtil.month(date) + 1;
            int count = monthMap.get(year + "-" + month + "月") + 1;
            monthMap.put(year + "-" + month + "月", count);
        }
        List<Object> xName = new ArrayList<>(monthMap.keySet());
        List<Object> yName = new ArrayList<>(monthMap.values());
        Map<String, Object> returnMap = new HashMap<>();
        returnMap.put("xName", xName);
        returnMap.put("yName", yName);
        return returnMap;
    }

    /**
     * 档案存取统计
     *
     * @return
     */
    public Map<String, Object> archiveAccessStatistics(String selectStartDate, String selectEndDate) throws ParseException {
        List<BorrowingRecords> archivesRecordList = null;
        Date nowDate = DateUtil.date();
        Map<String, Integer> lendingMap = null;
        Map<String, Integer> returnMap = null;
        if (StrUtil.isEmpty(selectStartDate) && StrUtil.isEmpty(selectEndDate)) {
            archivesRecordList = borrowingRecordsMapper.getInThePast6Months();
            Date newDate = DateUtil.offset(nowDate, DateField.MONTH, -6);
            lendingMap = new LinkedHashMap<String, Integer>() {
                {
                    for (int i = 0; i <= 6; i++) {
                        Date offsetNewDate = DateUtil.offset(newDate, DateField.MONTH, i);
                        int year = DateUtil.year(offsetNewDate);
                        int month = DateUtil.month(offsetNewDate) + 1;
                        put(year + "-" + month + "月", 0);

                    }
                }
            };
            returnMap = new LinkedHashMap<String, Integer>() {
                {
                    for (int i = 0; i <= 6; i++) {
                        Date offsetNewDate = DateUtil.offset(newDate, DateField.MONTH, i);
                        int year = DateUtil.year(offsetNewDate);
                        int month = DateUtil.month(offsetNewDate) + 1;
                        put(year + "-" + month + "月", 0);

                    }
                }
            };
        } else {
            Date startDate = DateUtil.parse(selectStartDate, "yyyy-MM-dd");
            String formatStartDate = DateUtil.format(startDate, "yyyy-MM-dd");
            Date endDate = DateUtil.parse(selectEndDate, "yyyy-MM-dd");
            String formatEndDate = DateUtil.format(endDate, "yyyy-MM-dd");
            archivesRecordList = borrowingRecordsMapper.getSpecifyData(formatStartDate, formatEndDate);
//            String format = DateUtil.format(nowDate, "yyyy-MM-dd");
            int monthDifference = DateFormat.getMonthSpace(selectStartDate, selectEndDate);
            lendingMap = new LinkedHashMap<String, Integer>() {
                {
                    for (int i = 0; i <= monthDifference; i++) {
                        Date offsetNewDate = DateUtil.offset(startDate, DateField.MONTH, i);
                        int year = DateUtil.year(offsetNewDate);
                        int month = DateUtil.month(offsetNewDate) + 1;
                        put(year + "-" + month + "月", 0);
                    }
                }
            };
            returnMap = new LinkedHashMap<String, Integer>() {
                {
                    for (int i = 0; i <= monthDifference; i++) {
                        Date offsetNewDate = DateUtil.offset(startDate, DateField.MONTH, i);
                        int year = DateUtil.year(offsetNewDate);
                        int month = DateUtil.month(offsetNewDate) + 1;
                        put(year + "-" + month + "月", 0);
                    }
                }
            };
        }
        for (BorrowingRecords borrowingRecords : archivesRecordList) {
            Date date = DateUtil.parse(borrowingRecords.getCreateTime(), "yyyy-MM-dd");
            int year = DateUtil.year(date);
            int month = DateUtil.month(date) + 1;
            if (borrowingRecords.getDataStatus() == 1 || borrowingRecords.getDataStatus() == 3) {
                int count = lendingMap.get(year + "-" + month + "月") + 1;
                returnMap.put(year + "-" + month + "月", count);
            }
            if (borrowingRecords.getDataStatus() == 0 || borrowingRecords.getDataStatus() == 2) {
                int count = returnMap.get(year + "-" + month + "月") + 1;
                lendingMap.put(year + "-" + month + "月", count);
            }
        }
        List<Object> xName = new ArrayList<>(lendingMap.keySet());
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("xName", xName);
        List<Object> lendingList = new ArrayList<>(lendingMap.values());
        resultMap.put("lendingList", lendingList);
        List<Object> returnList = new ArrayList<>(returnMap.values());
        resultMap.put("returnList", returnList);
        return resultMap;
    }

    /**
     * 二维码页面
     */
    public ModelAndView qrCode(String fileName, String uuid) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("archives/qrCode");
        if (fileName.length() > 5) {
            fileName = fileName.substring(0, 5) + "...";
        }
        modelAndView.addObject("fileName", fileName);
        modelAndView.addObject("date", DateFormat.getDate());
        modelAndView.addObject("uuid", uuid);
        return modelAndView;
    }

    /**
     * 扫码枪获取档案信息
     */
    public ResponseModel scannerGetArchives(String uuid) {
        String[] uuids = uuid.split(":");
        Map<String, Object> archives = archivesMapper.scannerGetArchives(uuids[1]);
        if (archives == null) {
            return ResponseModel.fail("未找到档案信息");
        }
        int archiveStatus = Convert.toInt(archives.get("status"));
        if (archiveStatus == 0) {
            archives.put("status", "在库");
            archives.put("statusCode", 0);
        } else if (archiveStatus == 1) {
            archives.put("status", "出库");
            archives.put("statusCode", 1);
        } else if (archiveStatus == 2) {
            archives.put("status", "出库未取走");
            archives.put("statusCode", 0);
        } else if (archiveStatus == 3) {
            archives.put("status", "归还未入库");
            archives.put("statusCode", 1);
        }
        // 获取区号
        Host host = hostService.getOne(new QueryWrapper<Host>().eq("cabinet_number", Convert.toInt(archives.get("areaCode"))));
        if (host != null) {
            archives.put("areaCode", "载体名称: " + host.getCabinetName() + " " + "区号: " + host.getCabinetNumber());
        }

        if (Convert.toInt(archives.get("denseRackRegion")) == 0) {
            archives.put("denseRackRegion", "左区");
        } else {
            archives.put("denseRackRegion", "右区");

        }
        return ResponseModel.success(archives, "获取成功");
    }

    /**
     * 扫码枪入库
     */
    public ResponseModel scannerGunIn(JSONObject data) throws InterruptedException {
        String[] uuids = data.getStr("uuid").split(":");
        Archives archives = archivesMapper.selectOne(new QueryWrapper<Archives>().eq("uuid", uuids[1]));
        if (archives != null) {
            String sysType = sysType();
            QueryWrapper<Host> hostQueryWrapper = new QueryWrapper<>();
            hostQueryWrapper.eq("cabinet_number", archives.getAreaCode());
            Host host = hostService.getOne(hostQueryWrapper);
            if (!sysType.equals("4")) {
                // 设备状态检查
                if (!getDeviceStatus(host)) {
                    return ResponseModel.fail("设备未连接，请确认设备开启状态");
                }
                // 下发借阅通知
                String position = null;
                Map<String, Object> restoreMap = new HashMap<>();
                if (sysType.equals("1") || sysType.equals("3")) {
                    restoreMap.put("type", "task");
                    position = getPosition(archives, sysType);
                    restoreMap.put("operation", "restore");
                    restoreMap.put("filename", archives.getFileName());
                    restoreMap.put("fileId", archives.getId()); //数据库自增id
                    restoreMap.put("rfid", archives.getFileId());
                    restoreMap.put("barcode", "");
                    restoreMap.put("reserved", "");
                } else {
                    restoreMap.put("type", "open_lie_lock");
                    position = mapCabinetPosition(archives);
                }
                restoreMap.put("position", position);
                String lockStrMap = JSONUtil.toJsonStr(restoreMap);
                sendCmd.send(lockStrMap, null, host.getIp());
                // 开灯
                openLen(position, host.getIp());
            }
            // 修改档案状态
            UpdateWrapper<Archives> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("id", archives.getId());
            if (sysType.equals("1") || sysType.equals("3")) {
                updateWrapper.set("status", 3);
            } else {
                updateWrapper.set("status", 0);
            }
            updateWrapper.set("update_time", DateFormat.getTime());
            int result = archivesMapper.update(null, updateWrapper);
            if (result <= 0) {
                return ResponseModel.fail("档案归还失败");
            }

            //添加借阅记录
            JwtUserDto jwtUserDto = (JwtUserDto) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            String userName = jwtUserDto.getUsername();
            BorrowingRecords borrowingRecords = new BorrowingRecords();
            borrowingRecords.setFileId(archives.getId());
            borrowingRecords.setFileName(archives.getFileName());
            borrowingRecords.setDeptId(jwtUserDto.getMyUser().getDeptId());
            borrowingRecords.setUserName(userName);
            borrowingRecords.setRemarks("扫码枪入库");
            borrowingRecords.setCreateTime(DateFormat.getTime());
            if (sysType.equals("1") || sysType.equals("3")) {
                borrowingRecords.setDataStatus(3);
            } else {
                borrowingRecords.setDataStatus(1);
            }
            borrowingRecords.setStatus(1);
            borrowingRecords.setModuleType(2);
            borrowingRecords.setOperation(userName + "用户归还" + archives.getFileName() + "档案");
            borrowingRecords.setHostId(host.getId());
            borrowingRecordsMapper.insert(borrowingRecords);
            if (sysType.equals("1") || sysType.equals("3")) {
                return ResponseModel.success("请前往柜体端归还档案");
            } else {
                return ResponseModel.success("档案归还成功");
            }
        } else {
            return ResponseModel.fail("未找到档案信息");
        }
    }

    /**
     * 扫码枪出库
     */
    public ResponseModel scannerGunOut(JSONObject data) throws InterruptedException {
        String[] uuids = data.getStr("uuid").split(":");
        Archives archives = archivesMapper.selectOne(new QueryWrapper<Archives>().eq("uuid", uuids[1]));
        if (archives != null) {
            // 下发借阅通知
            String sysType = sysType();
            QueryWrapper<Host> hostQueryWrapper = new QueryWrapper<>();
            hostQueryWrapper.eq("cabinet_number", archives.getAreaCode());
            Host host = hostService.getOne(hostQueryWrapper);
            if (!sysType.equals("4")) {
                // 设备状态检查
                if (!getDeviceStatus(host)) {
                    return ResponseModel.fail("设备未连接，请确认设备开启状态");
                }
                // 下发借阅通知
                String position = null;
                Map<String, Object> borrowingMap = new HashMap<>();
                if (sysType.equals("1") || sysType.equals("3")) {
                    borrowingMap.put("type", "task");
                    position = getPosition(archives, sysType);
                    borrowingMap.put("operation", "borrow");
                    borrowingMap.put("filename", archives.getFileName());
                    borrowingMap.put("fileId", archives.getId()); //数据库自增id
                    borrowingMap.put("rfid", archives.getFileId());
                    borrowingMap.put("barcode", "");
                    borrowingMap.put("reserved", "");
                } else {
                    borrowingMap.put("type", "open_lie_lock");
                    position = mapCabinetPosition(archives);
                }
                borrowingMap.put("position", position);
                String lockStrMap = JSONUtil.toJsonStr(borrowingMap);
                sendCmd.send(lockStrMap, null, host.getIp());
                // 开灯
                openLen(position, host.getIp());
            }
            // 修改档案状态
            UpdateWrapper<Archives> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("id", archives.getId());
            if (sysType.equals("1") || sysType.equals("3")) {
                updateWrapper.set("status", 2);
            } else {
                updateWrapper.set("status", 1);
            }
            updateWrapper.set("update_time", DateFormat.getTime());
            int result = archivesMapper.update(null, updateWrapper);
            if (result <= 0) {
                return ResponseModel.fail("档案借阅失败");
            }

            //添加借阅记录
            JwtUserDto jwtUserDto = (JwtUserDto) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            String userName = jwtUserDto.getUsername();
            BorrowingRecords borrowingRecords = new BorrowingRecords();
            borrowingRecords.setFileId(archives.getId());
            borrowingRecords.setFileName(archives.getFileName());
            borrowingRecords.setDeptId(jwtUserDto.getMyUser().getDeptId());
            borrowingRecords.setUserName(userName);
            borrowingRecords.setRemarks("扫码枪出库");
            borrowingRecords.setCreateTime(DateFormat.getTime());
            if (sysType.equals("1") || sysType.equals("3")) {
                borrowingRecords.setDataStatus(2);
            } else {
                borrowingRecords.setDataStatus(0);
            }
            borrowingRecords.setStatus(1);
            borrowingRecords.setModuleType(2);
            borrowingRecords.setOperation(userName + "用户借阅" + archives.getFileName() + "档案");
            borrowingRecords.setHostId(host.getId());
            borrowingRecordsMapper.insert(borrowingRecords);
            if (sysType.equals("1") || sysType.equals("3")) {
                return ResponseModel.success("请前往柜体端领取档案");
            } else {
                return ResponseModel.success("档案领取成功");
            }
        } else {
            return ResponseModel.fail("未找到档案信息");
        }
    }

}
